//
//  TDCheckNewPayC.m
//  TBRentClient
//
//  Created by tonbright on 2018/7/5.
//  Copyright © 2018年 tonbright. All rights reserved.
//

#import "TDCheckNewPayC.h"

#import "TDCheckPayCarDescCell.h"
#import "TDCheckPaySelPayTypeCell.h"
#import "TDCheckPayCarBaiscCell.h"
#import "TDCheckPayNoSelTypeCell.h"
#import "TDSurePayBtnCell.h"
#import "TDYuDingCarSectionHeadView.h"
#import "NetWorkRequest.h"
#import "PaymentObject.h"
#import "UINavigationController+SXFullScreen.h"
#import "BaseOperation.h"
#import "TDCarDetailC.h"
#import "YXDateHelpObject.h"
#import "TDPayResultShowC.h"
#import "TDPayResultErrorShowC.h"
#import "TDCheckPayModel.h"
@interface TDCheckNewPayC ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, assign) BOOL isWxPay;

@end

@implementation TDCheckNewPayC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self setupUI];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    
}

- (IBAction)navBtnClick:(UIButton *)sender {
    [self.view endEditing:YES];
    __weak typeof(self) weakSelf = self;
    [[BaseOperation shareManager] alertShow:self Message:@"订单尚未支付成功,是否返回?"];
    [BaseOperation shareManager].actionCancle = ^ {
        
    };
    [BaseOperation shareManager].actionSure = ^ {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.navigationController popViewControllerAnimated:YES];
    };
}

- (void)setupUI {
    //设置导航条
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDCheckPayCarDescCell" bundle:nil] forCellReuseIdentifier:@"TDCheckPayCarDescCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDCheckPaySelPayTypeCell" bundle:nil] forCellReuseIdentifier:@"TDCheckPaySelPayTypeCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDCheckPayCarBaiscCell" bundle:nil] forCellReuseIdentifier:@"TDCheckPayCarBaiscCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDCheckPayNoSelTypeCell" bundle:nil] forCellReuseIdentifier:@"TDCheckPayNoSelTypeCellId"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"TDSurePayBtnCell" bundle:nil] forCellReuseIdentifier:@"TDSurePayBtnCellId"];
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, -10, 0, -10)];
    }
    self.sx_disableInteractivePop = YES;
    
}



#pragma mark - 返回组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark - 返回行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // MARK: - 判断如果有优惠券就返回4  没优惠券就返回3
    return 5;
}

#pragma mark - 返回每行内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //自定义cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[self getIdentifier:indexPath] forIndexPath:indexPath];
    [self setupCell:cell indexPath:indexPath];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 135;
    }else if (indexPath.row == 1) {
        //如果金额是0的话就是
        return 186;
    }else if (indexPath.row == 4) {
        return 130;
    }else {
        return 50;
    }
    return 50;
}

- (NSString *)getIdentifier:(NSIndexPath *)indexPath {
    NSString *iden = @"TDCheckPayCarDescCellId";
    if (indexPath.row == 0) {
        iden = @"TDCheckPayCarDescCellId";
    }else if (indexPath.row == 1) {
        //如果金额是0的话就是
        iden = @"TDCheckPaySelPayTypeCellId";
    }else if (indexPath.row == 4) {
        iden = @"TDSurePayBtnCellId";
    }else{
        iden = @"TDCheckPayCarBaiscCellId";
    }
    return iden;
    //#import "TDCheckPayCarDescCell.h"
    //#import "TDCheckPaySelPayTypeCell.h"
    //#import "TDCheckPayCarBaiscCell.h"
    //#import "TDCheckPayNoSelTypeCell.h"
}

- (void)setupCell:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0) {
        TDCheckPayCarDescCell *checkPayCarDescCell = (TDCheckPayCarDescCell *)cell;
        checkPayCarDescCell.lbe_brandnm.text = [NSString stringWithFormat:@"%@ %@",_orderDetailModel.brandnm,_orderDetailModel.seriesnm];
        checkPayCarDescCell.lbe_typenm.text = _orderDetailModel.typenm;
        NSString *imgStr = [NSString stringWithFormat:@"http://121.40.92.131/deepdriving/%@",_orderDetailModel.rstorelogo];
        [checkPayCarDescCell.imv_carImg sd_setImageWithURL:[NSURL URLWithString:imgStr] placeholderImage:[UIImage imageNamed:@"car"]];
        
        NSString *pickTime = [[YXDateHelpObject manager] getStrDateFromStrDate:self.orderDetailModel.planpickuptime OldFormat:@"yyyy-MM-dd HH:mm:ss" ByNewFormat:@"MM月dd日 HH:mm"];
        NSString *returnTime = [[YXDateHelpObject manager] getStrDateFromStrDate:self.orderDetailModel.planreturntime OldFormat:@"yyyy-MM-dd HH:mm:ss" ByNewFormat:@"MM月dd日 HH:mm"];
        checkPayCarDescCell.lbe_tdTime.text = [NSString stringWithFormat:@"%@ 至 %@",pickTime,returnTime];
    }else if (indexPath.row == 1) {
        //如果金额是0的话就是
        TDCheckPaySelPayTypeCell *checkPaySelPayTypeCell = (TDCheckPaySelPayTypeCell *)cell;
        __weak typeof(self) weakSelf = self;
        
        if (_orderDetailModel.totalpayamount.floatValue <= 0) {
            checkPaySelPayTypeCell.view_hiden.hidden = NO;
        }else {
            checkPaySelPayTypeCell.view_hiden.hidden = YES;
        }
        
        
        checkPaySelPayTypeCell.lbe_basePrice.text = [NSString stringWithFormat:@"¥ %@ x %@天",_orderDetailModel.dayprice,_orderDetailModel.reservedays];
        checkPaySelPayTypeCell.lbe_totalPrice.text = [NSString stringWithFormat:@"¥ %@",_orderDetailModel.totalbaseamount];
        checkPaySelPayTypeCell.checkSelPayTypeBtnClickBlock = ^(NSInteger selType) {
            weakSelf.isWxPay = selType == 10;
        };
    }else if (indexPath.row == 4) {
        TDSurePayBtnCell *surePayBtnCell = (TDSurePayBtnCell *)cell;
        __weak typeof(self) weakSelf = self;
        surePayBtnCell.SurePayBtnCellBlock = ^{
            [weakSelf payBtnClick];
        };
    }else{
        TDCheckPayCarBaiscCell *checkPayCarBaiscCell = (TDCheckPayCarBaiscCell *)cell;
        if (indexPath.row == 2) {
            checkPayCarBaiscCell.lbe_desc.text = @"试驾券";
            checkPayCarBaiscCell.lbe_detail.text = self.orderDetailModel.totaldiscount ? [NSString stringWithFormat:@"-¥ %@",_orderDetailModel.totaldiscount] : @"0";
            
        }else if (indexPath.row == 3) {
            checkPayCarBaiscCell.lbe_desc.text = @"总额";
            checkPayCarBaiscCell.lbe_detail.text = _orderDetailModel.totalpayamount;
        }
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    TDYuDingCarSectionHeadView *headView = [TDYuDingCarSectionHeadView yuDingCarSectionHeadView];
    headView.lbe_title.text = @"检查并支付";
    headView.frame = CGRectMake(0, 0, Width-20, 74);
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 74;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}



// MARK: - 加载数据
- (void)loadData {
    _isWxPay = YES;
    self.orderid = _orderDetailModel.orderid;
    self.orderno = _orderDetailModel.orderno;
    self.updatetime = _orderDetailModel.updatetime;
    [self loadNetData];
}


// MARK: - 获取网络数据-----
- (void)loadNetData {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showWXPayResult:) name:@"kWXPayResult" object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)showWXPayResult:(NSNotification *)noti {
    NSDictionary *userinfo = noti.userInfo;
    NSString *payResult = userinfo[@"code"];
    if ([payResult isEqualToString:@"1"]) {
        TDPayResultShowC *payResultShowC = [[TDPayResultShowC alloc] init];
        payResultShowC.isFromDingDan = YES;
        [self.navigationController pushViewController:payResultShowC animated:YES];
    }else {
        TDPayResultErrorShowC *payEroResultShowC = [[TDPayResultErrorShowC alloc] init];
        payEroResultShowC.isFromDingDan = YES;
        [self.navigationController pushViewController:payEroResultShowC animated:YES];
    }
}


// MARK: - 支付按钮点击事件--------
- (void)payBtnClick {
    //如果不用支付的情况下---------
    if (_orderDetailModel.totalpayamount.floatValue <= 0) {
        [self originPay];
        return;
    }
    
    //需要用支付宝和微信支付的情况下-------
    if (self.isWxPay) {
        [self wxPay];
    }else {
        [self aliPay];
    }
}


- (void)wxPay {
    // MARK: - 写死的假数据  哈哈哈 记得修改---------
    NSDictionary *parDic = @{
                             @"stage":@"1",
                             @"updateuserid":[AppSetting shareAppSetting].memberid,
                             @"orderid":self.orderid,
                             @"orderno":self.orderno
                             };
    __weak typeof(self) weakSelf = self;
    [self progressHUDShowWithText:nil];
    [NetWorkRequest postNetRequestData:OrderWXPay parmeters:parDic response:^(NSDictionary *response) {
        if (response) {
            [weakSelf progressHUDHideImmediately];
            [[PaymentObject sharePayMange] wxPayAcion:response[@"data"]];
        }else {
            [weakSelf progressHUDHideImmediately];
        }
    } netError:^(NSError *error) {
        [weakSelf progressHUDShowWithCompleteText:nil isSucceed:NO];
    }];
}

- (void)aliPay {
    self.noticeText = @"支付宝支付";
    return;
}

- (void)originPay {
    // MARK: - 写死的假数据  哈哈哈 记得修改---------
    TDCheckPayModel *checkPayModel = [[TDCheckPayModel alloc] init];
    TDOrderDetailListModel *orderDetailListModel = self.orderDetailModel.orderdetaillist.firstObject;
    checkPayModel.seqid = @"1";
    checkPayModel.stage = @"1";
    checkPayModel.paytype = @"8";
    checkPayModel.amount = _orderDetailModel.totaldiscount;
    checkPayModel.refdocno = _orderDetailModel.couponno;
    NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
    [tmpArray addObject:checkPayModel];
    
    NSDictionary *parDic = @{
                             @"stage":@"1",
                             @"updateuserid":[AppSetting shareAppSetting].memberid,
                             @"orderid":self.orderid,
                             @"orderno":self.orderno,
                             @"paydetaillist":[tmpArray yy_modelToJSONString]
                             };
    __weak typeof(self) weakSelf = self;
    [self progressHUDShowWithText:nil];
    [NetWorkRequest postNetRequestData:OrderOriginPay parmeters:parDic response:^(NSDictionary *response) {
        
        if (response) {
            [weakSelf progressHUDHideImmediately];
            TDPayResultShowC *payResultShowC = [[TDPayResultShowC alloc] init];
            payResultShowC.isFromDingDan = YES;
            [weakSelf.navigationController pushViewController:payResultShowC animated:YES];
            
        }else {
            [weakSelf progressHUDHideImmediately];
            TDPayResultErrorShowC *payResultShowC = [[TDPayResultErrorShowC alloc] init];
            payResultShowC.isFromDingDan = YES;
            [weakSelf.navigationController pushViewController:payResultShowC animated:YES];
        }
    } netError:^(NSError *error) {
        [weakSelf progressHUDShowWithCompleteText:nil isSucceed:NO];
        TDPayResultErrorShowC *payResultShowC = [[TDPayResultErrorShowC alloc] init];
        payResultShowC.isFromDingDan = YES;
        [weakSelf.navigationController pushViewController:payResultShowC animated:YES];
    }];
}

@end
